#include "tlogindialog.h"
#include "ui_tlogindialog.h"

#include <QMouseEvent>
#include <QCryptographicHash> // for 加密
#include <QSettings>
#include <QMessageBox>

TLoginDialog::TLoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TLoginDialog)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);
    setWindowFlags(Qt::SplashScreen);
//    setWindowFlags(Qt::FramelessWindowHint); // 无边框

    QApplication::setOrganizationName("AXB-QT");
    QApplication::setApplicationName("sample7-5");
    readSettings();
}

TLoginDialog::~TLoginDialog()
{
    delete ui;
}

QString TLoginDialog::encrypt(const QString &str)
{
    QCryptographicHash hash(QCryptographicHash::Md5); // 选择加密算法
    hash.addData(str.toLocal8Bit());
    return hash.result();
}

void TLoginDialog::readSettings()
{
    // 从注册表读取数据
    QSettings settings;
    bool saved = settings.value("saved", false).toBool();
    m_user = settings.value("Username", "user").toString();
     m_password = encrypt("12345");
//     m_password = settings.value("Password", encrypt("12345").toString();
    if (saved) {
        ui->editUsername->setText(m_user);
    }
    ui->chkSave->setChecked(true);
}

void TLoginDialog::writeSettings()
{
    // 将数据保存到注册表
    QSettings settings;
    settings.setValue("Username", m_user);
    settings.setValue("Password", m_password);
    settings.setValue("saved", ui->chkSave->isChecked());
}

void TLoginDialog::mousePressEvent(QMouseEvent *event)
{
    QPoint eventPos = event->globalPosition().toPoint();
    if (event->button() == Qt::LeftButton) {
        m_moving = true;
        m_lastPos = eventPos;
    }
    return QDialog::mousePressEvent(event);
}

void TLoginDialog::mouseReleaseEvent(QMouseEvent *event)
{
    m_moving = false;
    event->accept();
}

void TLoginDialog::mouseMoveEvent(QMouseEvent *event)
{
    QPoint eventPos = event->globalPosition().toPoint();
    QPoint moveVector = eventPos - m_lastPos;

    if (m_moving && (event->buttons() & Qt::LeftButton) &&
        (moveVector.manhattanLength() > QApplication::startDragDistance())) {
        move(pos() + moveVector);
        m_lastPos = eventPos;
    }

    return QDialog::mouseMoveEvent(event);
}

void TLoginDialog::on_btnOK_clicked()
{
    QString user = ui->editUsername->text().trimmed();
    QString password = ui->editPassword->text().trimmed();
    QString encryptPassword = encrypt(password);
    if ((user == m_user) && (encryptPassword == m_password)) {
        writeSettings();
        this->accept();
    }
    else {
        m_tryCount++;
        if (m_tryCount >= kMaxCount) {
            QMessageBox::critical(this, "错误", "输入错误次数太多!");
            this->reject();
        }
        else {
            QMessageBox::warning(this, "错误提示", "用户名密码错误");
        }
    }
}

